//
//  RenZhengMarketController.m
//  Experss
//
//  Created by 嗯，大葱 on 17/8/8.
//  Copyright © 2017年 嗯，大葱. All rights reserved.
//

#import "RenZhengMarketController.h"
#import "RenZhengOneCell.h"
#import "RenZhengTwoCell.h"
#import "RenZhengThirdCell.h"
#import "STPhotoKitController.h"
#import "UIImagePickerController+ST.h"

#import "PayResultView.h"//支付结果视图

//区分进入相册或者调用相机
typedef NS_ENUM(NSInteger, PhotoType)
{
    PhotoTypeIcon,
    PhotoTypeRectangle,
    PhotoTypeRectangle1
};

@interface RenZhengMarketController ()<UITableViewDelegate, UITableViewDataSource,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate,STPhotoKitDelegate,payResultBackBtnDelegate>
{
    
    NSString *nameStr;
    NSString *shenfenZhenStr;
    NSString *chaoshiNameStr;
    NSString *yingYZhiZhaoNumStr;
    NSString *chaoshiAddressStr;
    
     NSString *photoStr1;
     NSString *photoStr2;
     NSString *photoStr3;
    
    UIImage *imageOne;
    UIImage *imageTwo;
    UIImage *imagethird;
   
    
    
    
    
    BOOL flag;//用来判断删除照片的按钮是否隐藏
    BOOL flag2;//用来判断删除照片的按钮是否隐藏
    BOOL flag3;//用来判断删除照片的按钮是否隐藏
    
}

@property (nonatomic, strong)NSArray *titleA;
@property (nonatomic, strong)NSArray *titleA2;
@property (nonatomic, assign) PhotoType type;
@property (nonatomic, strong)PayResultView *payResultView;




@end

@implementation RenZhengMarketController
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    if (_payResultView) {
        [_payResultView removeFromSuperview];
    }
    
}
- (void)selectedIcon
{
    self.type = PhotoTypeIcon;
    [self editImageSelected];
}

- (void)selectedRectangle{
    self.type = PhotoTypeRectangle;
    [self editImageSelected];
}


- (void)selectedRectangle1{
    self.type = PhotoTypeRectangle1;
    [self editImageSelected];
}
#pragma mark - --- event response 事件相应 ---
- (void)editImageSelected
{
    UIAlertController *alertController = [[UIAlertController alloc]init];
    
    UIAlertAction *action0 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypeCamera];
        
        if ([controller isAvailableCamera] && [controller isSupportTakingPhotos]) {
            [controller setDelegate:self];
            [self presentViewController:controller animated:YES completion:nil];
        }else {
            NSLog(@"%s %@", __FUNCTION__, @"相机权限受限");
        }
    }];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"从相册获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        [controller setDelegate:self];
        if ([controller isAvailablePhotoLibrary]) {
            [self presentViewController:controller animated:YES completion:nil];
        }    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alertController addAction:action0];
    [alertController addAction:action1];
    [alertController addAction:action2];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)photoKitController:(STPhotoKitController *)photoKitController resultImage:(UIImage *)resultImage
{
    switch (self.type) {
        case PhotoTypeIcon:
           imageOne = resultImage;
            
            break;
        case PhotoTypeRectangle:
            imageTwo = resultImage;
            break;
        case PhotoTypeRectangle1:
            imagethird = resultImage;
            break;
        default:
            break;
    }
}
#pragma mark - 2.UIImagePickerController的委托

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *imageOriginal = [info objectForKey:UIImagePickerControllerOriginalImage];
   
        switch (self.type) {
            case PhotoTypeIcon:
                NSLog(@"-----------------%@",imageOriginal);
            

                imageOne = imageOriginal;
                flag = NO;
                //压缩图片
                [self postImage:imageOne];
                [self reloadOneinspath:2 :0];
                
                
                
                break;
                
            case PhotoTypeRectangle:
                NSLog(@"-----------------%@",imageOriginal);
                imageTwo = imageOriginal;
             
                flag2 = NO;
                [self postImage:imageTwo];
                [self reloadOneinspath:2 :0];
                break;
            case PhotoTypeRectangle1:
                NSLog(@"-----------------%@",imageOriginal);
                imagethird = imageOriginal;
                
                flag3 = NO;
                [self postImage:imagethird];
                [self reloadOneinspath:3 :0];
                break;
                
            default:
                break;
        }
        
    }];
}
- (void)postImage:(UIImage *)iamge {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //压缩图片
    NSData *fileData = UIImageJPEGRepresentation(iamge, 0.0);
    NSDictionary *dic = @{@"file":fileData};

    AFHTTPSessionManager *Manager = [AFHTTPSessionManager manager];
    Manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/plain",@"text/html", nil];
    
    [Manager POST:POST(FileURL) parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:fileData name:@"file" fileName:@"file.png" mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"ret"] intValue] != 200)  {
            return ;
        }
        
        
        NSLog(@"返回的图片地址%@",responseObject);
        if (iamge == imageOne) {
            photoStr1 = responseObject[@"data"][@"info"][@"url"];
        }
        if (iamge == imageTwo) {
            photoStr2 = responseObject[@"data"][@"info"][@"url"];
        }
        if (iamge == imagethird) {
            photoStr3 = responseObject[@"data"][@"info"][@"url"];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.view showTextNoActivity:@"服务器异常" timeLength:1];
    }];
    
    /*
    [HttpRequest upLoadImageWithURLString:POST(FileURL) imageData:fileData parameters:dic progerss:^{
        
    } success:^(id responseObject){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        NSLog(@"%@-------",responseObject);
    } failure:^(NSError *error) {
        NSLog(@"更换头像获取token == %@",error);
        
    }];*/
    
}
- (void) reloadOneinspath:(NSInteger )section :(NSInteger)row {
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:row inSection:section];
    [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

- (void)viewDidLoad{
    [super viewDidLoad];
    flag = YES;
    flag2 = YES;
    flag3 = YES;
    _titleA = @[@[@"姓名",@"身份证",@"超市名称"],@[@"营业执照",@"超市地址"]];
    _titleA2 = @[@[@"请输入真实姓名",@"请输入身份证号码",@"请输入超市名称"],@[@"请输入营业执照注册号",@"请输入超市具体地址"]];
    [self configureNaBar];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = kSpNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"RenZhengOneCell" bundle:nil] forCellReuseIdentifier:@"RenZhengOneCell"];
     [self.tableView registerNib:[UINib nibWithNibName:@"RenZhengTwoCell" bundle:nil] forCellReuseIdentifier:@"RenZhengTwoCell"];
     [self.tableView registerNib:[UINib nibWithNibName:@"RenZhengThirdCell" bundle:nil] forCellReuseIdentifier:@"RenZhengThirdCell"];
    imageOne = [UIImage imageNamed:@"chaoshirenzhen_tupian"];
    imageTwo =[UIImage imageNamed:@"chaoshirenzhen_tupian"];
    imagethird =[UIImage imageNamed:@"chaoshirenzhen_tupian"];
   
}


- (void)configureNaBar {
    self.navigationItem.title = @"超市认证";
    //设置导航栏按钮的边距
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame= CGRectMake(0, 0, 60, 30);
    [rightBtn setImage:[UIImage imageNamed:@"all_fanhui2"] forState:(UIControlStateNormal)];
    [rightBtn addTarget:self action:@selector(handleBackAxtion) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    UIBarButtonItem *negativeSpacerleft = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    /**
     width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和  边界间距为5pix，所以width设为-5时，间距正好调整为0；width为正数 时，正好相反，相当于往左移动width数值个像素
     */
    negativeSpacerleft.width = -20;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacerleft, btn_left, nil];
    

    
}

- (void)handleBackAxtion {
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 3;
    }
    if (section == 1) {
        return 2;
    }else {
        return 1;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 2  || indexPath.section == 3) {
        return 200;
    }
    else {
        return 60;
    }
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 2 || section == 3) {
        return 30;
    }else {
    return 10;
    }
    
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 2 || section ==3) {
        UIView *view= [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 30)];
        view.backgroundColor = KShouYeBg;
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 200, 30)];
        label.textColor = [UIColor lightGrayColor];
        label.backgroundColor = KShouYeBg;
        label.font = kFont14;
        
        if (section == 2) {
            label.text = @"上传身份证";
        }
        if (section == 3) {
            label.text = @"上传营业执照";
        }
        [view addSubview:label];
        return view;
    }else {
        UIView *view= [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 10)];
        view.backgroundColor = KShouYeBg;
        
        
        
        return view;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        RenZhengOneCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RenZhengOneCell"];
        cell.selectionStyle = kSeNone;
        
        cell.titlLB.text = _titleA[0][indexPath.row];
        cell.conTF.placeholder = _titleA2[0][indexPath.row];
        cell.conTF.tag = 700+indexPath.row;
        [cell.conTF addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
        return cell;
    }
    if (indexPath.section == 1) {
        RenZhengOneCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RenZhengOneCell"];
        cell.selectionStyle = kSeNone;
        cell.titlLB.text = _titleA[1][indexPath.row];
        cell.conTF.placeholder = _titleA2[1][indexPath.row];
        cell.conTF.tag = 800+indexPath.row;
        [cell.conTF addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
        return cell;
    }
    if (indexPath.section == 2) {
        RenZhengTwoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RenZhengTwoCell"];
        cell.selectionStyle = kSeNone;
        cell.cardOneImage.image = imageOne;
        cell.cardTwoImage.image = imageTwo;
        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectedIcon)];
        
        cell.cardOneImage.userInteractionEnabled = YES;
        [ cell.cardOneImage addGestureRecognizer:tap1];
        
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectedRectangle)];
         cell.cardTwoImage.userInteractionEnabled = YES;
        [cell.cardTwoImage addGestureRecognizer:tap2];
       
        cell.remoBtn.hidden = flag;
        cell.remoBtn2.hidden = flag2;
        cell.remoBtn.tag = 701;
        cell.remoBtn2.tag = 702;
        [cell.remoBtn addTarget:self action:@selector(handleRemoImage:) forControlEvents:(UIControlEventTouchUpInside)];
        [cell.remoBtn2 addTarget:self action:@selector(handleRemoImage:) forControlEvents:(UIControlEventTouchUpInside)];
        
        return cell;
    }
   else {
        RenZhengThirdCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RenZhengThirdCell"];
       cell.selectionStyle = kSeNone;
       cell.yinyeOneImage.image = imagethird;
       UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectedRectangle1)];
       cell.yinyeOneImage.userInteractionEnabled = YES;
       [cell.yinyeOneImage addGestureRecognizer:tap3];
       cell.remoBtn3.hidden = flag3;
        [cell.remoBtn3 addTarget:self action:@selector(handleRemoThirdImage2:) forControlEvents:(UIControlEventTouchUpInside)];
        return cell;
    }
}
#pragma mark 提交身份照的编辑

- (void)handleRemoImage:(UIButton *)sender {
   
    RenZhengTwoCell *cell = (RenZhengTwoCell *)[[sender superview] superview];
    if (sender.tag == 701) {
        cell.cardOneImage.image = [UIImage imageNamed:@"chaoshirenzhen_tupian"];
        imageOne =[UIImage imageNamed:@"chaoshirenzhen_tupian"];
        sender.hidden = YES;
        flag  = YES;
     
    }
    if (sender.tag == 702) {
        cell.cardTwoImage.image =[UIImage imageNamed:@"chaoshirenzhen_tupian"];
        imageTwo =[UIImage imageNamed:@"chaoshirenzhen_tupian"];
        sender.hidden = YES;
       flag2  = YES;
    }
}

#pragma mark 提交营业执照的编辑
//最后一个分区的照片的编辑
- (void)handleRemoThirdImage2:(UIButton *)sender {
    RenZhengThirdCell *cell = (RenZhengThirdCell *)[[sender superview] superview];
    cell.yinyeOneImage.image = [UIImage imageNamed:@"chaoshirenzhen_tupian"];
    imagethird =[UIImage imageNamed:@"chaoshirenzhen_tupian"];
    sender.hidden = YES;
    flag3  = YES;
}

//确认按钮
- (IBAction)sureBtn:(UIButton *)sender {
 
    if ([self isBlankString:nameStr] == YES) {
        [self.view showTextNoActivity:@"请填写姓名" timeLength:1];
        return;
    }
    
    if ([self isBlankString:shenfenZhenStr] == YES) {
        [self.view showTextNoActivity:@"请填写身份证" timeLength:1];
        return;
    }
    
    if ([self isBlankString:chaoshiNameStr] == YES) {
        [self.view showTextNoActivity:@"请填写超市名称" timeLength:1];
        return;
    }
    
    
    if ([self isBlankString:yingYZhiZhaoNumStr] == YES) {
        [self.view showTextNoActivity:@"请填写营业执照" timeLength:1];
        return;
    }
    
    if ([self isBlankString:chaoshiAddressStr] == YES) {
        [self.view showTextNoActivity:@"请填写超市地址" timeLength:1];
        return;
    }
   
    if ([self isBlankString:photoStr1] == YES) {
        [self.view showTextNoActivity:@"请上传身份证正面照" timeLength:1];
        return;
    }
   
    if ([self isBlankString:photoStr2] == YES) {
        [self.view showTextNoActivity:@"请上传身份证反面照" timeLength:1];
        return;
    }
   
    if ([self isBlankString:photoStr3] == YES) {
        [self.view showTextNoActivity:@"请上传营业执照" timeLength:1];
        return;
    }
    
   
    NSDictionary *saveDic = [SaveDataMethord readLoginData];

    NSLog(@"-=-=-=%@%@%@",photoStr1,photoStr2,photoStr3);
    NSDictionary *dic = @{@"userid":saveDic[@"userid"],//用户id
                          @"is_alipay":@"0",//支付宝验证 1已验证 0未验证
                         @"name":nameStr,//姓名
                          @"idcard":shenfenZhenStr,//身份证
                          @"shop_name":chaoshiNameStr,//超市名称
                          @"license_number":yingYZhiZhaoNumStr,//营业执照编号
                          @"address":chaoshiAddressStr,//超市地址
                          @"idphoto_front":photoStr1,//身份证正面照
                          @"idphoto_back":photoStr2,//身份证反面照
                          @"license_photo":photoStr3,//营业执照
                          @"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]
                          };
    [HttpRequest postWithURLString:POST(ChaoShiRenzheng) parameters:dic success:^(id responseObject) {
        
        if ([responseObject[@"ret"] intValue] != 200) {
            [[DSLHUD shareDSLHUD] showTextNoActivity:@"上传资料出错" timeLength:1.5];
            return ;
        }
        if ([responseObject[@"data"] intValue] == -1) {
            [MBProgressHUD showText:@"上传资料失败,请重新尝试"];
            return;
        }
        if ([responseObject[@"data"] intValue] == 0) {
            //返回操作码，0表示成功 1已认证 2正在审核 -1审核提交失败 -2用户不存在 -3该用户被禁用
            
            if (_payResultView) {
                [_payResultView removeFromSuperview];
            }
            _payResultView = [[PayResultView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
            _payResultView.delegate = self;
            _payResultView.imageStr = @"tijiaochengg";
            _payResultView.payResultStr = @"提交成功";
            _payResultView.detailStr = @"后台正在审核中，三日内反馈结果";
            [[UIApplication sharedApplication].keyWindow addSubview:_payResultView];
        }
        if ([responseObject[@"data"] intValue] == 1) {
            [MBProgressHUD showText:@"已认证，请勿重复提交"];
            return;
        }
        
     
    } failure:^(NSError *error) {
        
    }];


}
//判断一个字符串是否为空
- (BOOL) isBlankString:(NSString *)string {
    
    if (string == nil || string == NULL) {
        
        return YES;
        
    }
    
    if ([string isKindOfClass:[NSNull class]]) {
        
        return YES;
        
    }
    
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        
        return YES;
        
    }
    
    return NO;
    
}


#pragma mark 监听输入框值的变化 
- (void)textFieldEditChanged:(UITextField *)textField {
    NSLog(@"%ld",textField.tag);
    switch (textField.tag) {
        case 700:
            nameStr = textField.text;
            break;
        case 701:
            shenfenZhenStr = textField.text;
            break;
        case 702:
            chaoshiNameStr = textField.text;
            break;
        case 800:
            yingYZhiZhaoNumStr = textField.text;
            break;
        case 801:
            chaoshiAddressStr = textField.text;
            break;
            
        default:
            break;
    }
    
    
    
}

- (void)payBackAction:(UIButton *)sender {
    if (_payResultView) {
        [_payResultView removeFromSuperview];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

@end
